package cn.kgc.reflect;

import cn.kgc.annotation.Bean;
import cn.kgc.annotation.Value;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author: mosin
 * @version: v1.0  2022/10/20
 * 通过反射操作类对象中的注解
 *
 */
public class ReflectDemo06 {

    public static void main(String[] args) {

        try {

            Class  clazz = Class.forName("cn.kgc.reflect.User");

            // 获取类对象中的注解
            Annotation[] annotations = clazz.getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println("annotation = " + annotation);
            }

            System.out.println("---------------getAnnotation-------------------");
            // 指定注解类型获取注解
            Bean annotation = (Bean) clazz.getAnnotation(Bean.class);
            System.out.println("annotation = " + annotation);

           //  如果获取注解中的参数值   ?
            String name = annotation.name();
            String value = annotation.value();
            System.out.println("value = " + value);
            System.out.println("name = " + name);


        } catch (Exception e) {
            e.printStackTrace();
        }


        try {

            Class aClass = Class.forName("cn.kgc.reflect.Person");
            Field personName = aClass.getDeclaredField("personName");
            personName.setAccessible(true);
            Value annotation = personName.getAnnotation(Value.class);
            String name = annotation.value();
            System.out.println("person name = " + name);

            Object o = aClass.newInstance();
            System.out.println("o = " + o);
            // 通过反射将注解中的值 设置在类对象中
            personName.set(o, name);
            System.out.println("o = " + o);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }





}
